package com.york.jobmew.circle.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.york.jobmew.circle.api.common.PageInfo;
import com.york.jobmew.circle.api.common.PageResult;
import com.york.jobmew.circle.api.enums.IsDeletedFlagEnum;
import com.york.jobmew.circle.api.req.GetShareMessageReq;
import com.york.jobmew.circle.api.vo.ShareMessageVO;
import com.york.jobmew.circle.server.dao.ShareMessageMapper;
import com.york.jobmew.circle.server.entity.po.ShareMessage;
import com.york.jobmew.circle.server.rpc.UserRpc;
import com.york.jobmew.circle.server.service.ShareMessageService;
import com.york.jobmew.circle.server.util.LoginUtil;
import com.york.jobmew.circle.server.websocket.JobMewSocket;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息表 服务实现类
 * 针对圈子中评论回复等，互相通知生成的消息
 */
@Service
public class ShareMessageServiceImpl extends ServiceImpl<ShareMessageMapper, ShareMessage> implements ShareMessageService {

    @Resource
    private JobMewSocket jobMewSocket;

    @Resource
    private UserRpc userRpc;


    /**
     * 获取消息
     *
     * @param req
     * @return
     */
    @Override
    public PageResult<ShareMessageVO> getMessages(GetShareMessageReq req) {

        LambdaQueryWrapper<ShareMessage> query = Wrappers.<ShareMessage>lambdaQuery()
                .eq(ShareMessage::getToId, LoginUtil.getLoginId())
                .eq(ShareMessage::getIsRead, req.getIsRead())
                .eq(ShareMessage::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode())
                .orderByDesc(ShareMessage::getId);

        PageInfo pageInfo = req.getPageInfo();
        Page<ShareMessage> page = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());

        // 根据queryWrapper获取分页信息
        Page<ShareMessage> pageRes = super.page(page, query);

        PageResult<ShareMessageVO> pageResult = new PageResult<>();
        List<ShareMessage> records = pageRes.getRecords();

        if (CollectionUtils.isNotEmpty(records)) {
            List<Long> ids = records.stream().map(ShareMessage::getId).collect(Collectors.toList());
            LambdaUpdateWrapper<ShareMessage> update = Wrappers.<ShareMessage>lambdaUpdate()
                    // 将消息置为已读
                    .set(ShareMessage::getIsRead, 1)
                    .in(ShareMessage::getId, ids);
            super.update(update);
        }

        List<ShareMessageVO> list = records.stream().map(item -> {
            ShareMessageVO vo = new ShareMessageVO();
            vo.setId(item.getId());
            vo.setContent(JSON.parseObject(item.getContent()));
            vo.setCreatedTime(item.getCreatedTime());
            return vo;
        }).collect(Collectors.toList());

        pageResult.setRecords(list);
        pageResult.setTotal((int) pageRes.getTotal());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setPageNo(pageInfo.getPageNo());
        return pageResult;
    }

    /**
     * 发起评论
     *
     * @param fromId   发起人
     * @param toId     收信人
     * @param targetId 动态id
     */
    @Override
    public void comment(String fromId, String toId, Long targetId) {

        JSONObject message = new JSONObject();

        // 1=评论 2=回复
        message.put("msgType", "COMMENT");
        message.put("msg", String.format("%s 评论了你的评论，快来看看吧!", userRpc.getUserInfo(fromId).getNickName()));
        message.put("targetId", targetId);

        ShareMessage shareMessage = new ShareMessage();
        shareMessage.setFromId(fromId);
        shareMessage.setToId(toId);
        shareMessage.setContent(message.toJSONString());
        shareMessage.setIsRead(2);
        shareMessage.setCreatedBy(fromId);
        shareMessage.setCreatedTime(new Date());
        shareMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        JobMewSocket socket = jobMewSocket.getJobMewSocket(toId);
        if (Objects.nonNull(socket)) {
            // 给收信人发送信息
            jobMewSocket.sendMessage(shareMessage.getContent(), socket.getSession());
        }
        // 存在数据库中
        super.save(shareMessage);
    }

    /**
     * 回复，同评论逻辑
     *
     * @param fromId   发起人
     * @param toId     收信人
     * @param targetId 动态id
     */
    @Override
    public void reply(String fromId, String toId, Long targetId) {

        JSONObject message = new JSONObject();
        // 1=评论 2=回复
        message.put("msgType", "COMMENT_REPLY");
        message.put("msg", String.format("%s 回复了你的评论，快来看看把！", userRpc.getUserInfo(fromId).getNickName()));
        message.put("targetId", targetId);

        ShareMessage shareMessage = new ShareMessage();
        shareMessage.setFromId(fromId);
        shareMessage.setToId(toId);
        shareMessage.setContent(message.toJSONString());
        shareMessage.setIsRead(2);
        shareMessage.setCreatedBy(fromId);
        shareMessage.setCreatedTime(new Date());
        shareMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        JobMewSocket socket = jobMewSocket.getJobMewSocket(toId);
        if (Objects.nonNull(socket)) {
            jobMewSocket.sendMessage(shareMessage.getContent(), socket.getSession());
        }
        super.save(shareMessage);

    }

    /**
     * 读消息
     * 当前用户读发给自己的消息
     *
     * @return
     */
    @Override
    public Boolean unRead() {
        LambdaQueryWrapper<ShareMessage> query = Wrappers.<ShareMessage>lambdaQuery()
                .eq(ShareMessage::getToId, LoginUtil.getLoginId())
                // 给未读消息设置为已读
                .eq(ShareMessage::getIsRead, 2)
                .eq(ShareMessage::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode());
        return super.count(query) > 0;
    }
}
